<script setup>
import {ref} from "vue";
import {useRouter} from "vue-router";
// 获取pinia的数据
import {useUserStore} from '@/stores/userStore'

const userStore = useUserStore()
// 登录表单
const loginForm = ref({
  username: 'admin',
  password: '123456',
  // agree:false
})
// 登录的loading
const loading = ref(false)
// 2. 准备规则对象
const loginRules = {
  username: [
    {required: true, message: '用户名不能为空', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {min: 6, max: 14, message: '密码长度为6-14个字符', trigger: 'blur'},
  ]
}

// 3. 获取form实例做统一校验
const ormRef = ref(null)
const router = useRouter()
const doLogin = () => {
  const {username, password} = loginForm.value
  // 调用实例方法
  ormRef.value.validate(async (valid) => {
    // valid: 所有表单都通过校验  才为true
    console.log(valid)
    console.log(loginForm)
    // 以valid做为判断条件 如果通过校验才执行登录逻辑
    if (valid) {
      await userStore.getUserInfo({username, password})
      // 1. 提示用户
      ElMessage({type: 'success', message: '登录成功'})
      // 2. 跳转首页
      await router.replace({path: '/'})
    }
  })
}
</script>

<template>
  <div id="login-app" class="login">
    <div class="login-box">
      <!--      <img src="../../images/login/loginbg.jpg" alt="">-->
      <div class="login-form">
        <el-form ref="ormRef" :model="loginForm" :rules="loginRules">
          <div class="login-form-title">
            <img alt="" src="../../assets/images/logo.png" style="width:150px;"/>
          </div>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" auto-complete="off" maxlength="20" placeholder="请输入您的账号"
                      type="text">
              <template #prefix>
                <el-icon class="iconfont icon-icon_user"></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" maxlength="20" placeholder="请输入您的密码" type="password">
              <template #prefix>
                <el-icon class="iconfont icon-lock"></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button :loading="loading" class="login-btn" style="width:100%;" type="primary"
                       @click.native.prevent="doLogin">
              <span v-if="!loading">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>

      </div>
    </div>
  </div>
</template>

<style scoped>
@import "@/styles/login.css";

#login-app {
  background-image: url('../../assets/images/loginbg.jpg');
  background-position: center;
}

i {
  font-size: 16px;
}


</style>